import ObjectPool from "../../../cfw/pool/ObjectPool";
import RandomHelper from "../../../cfw/tools/RandomHelper";
import { OPPSITE } from "../../../cfw/tools/Define";

const { ccclass, property } = cc._decorator;

@ccclass
export default class WaterStreamComp extends cc.Component {


    @property(cc.Node)
    waterPos: cc.Node = null;

    @property(cc.SpriteFrame)
    waterSprite: cc.SpriteFrame = null;

    @property([cc.Component.EventHandler])
    callback: cc.Component.EventHandler[] = [];

    @property(cc.Node)
    container: cc.Node = null;

    @property
    streamHigh: number = 400;


    protected pool: ObjectPool<cc.Node> = new ObjectPool('water')

    private startFlag: boolean = false;

    setStartFlag(flag: boolean) {
        this.startFlag = flag;
    }

    setStreamHigh(h: number) {
        this.streamHigh = h;
    }

    start() {

    }

    startWater() {
        let node = this.pool.get(() => {
            let n = new cc.Node()
            let sprite = n.addComponent(cc.Sprite)
            sprite.spriteFrame = this.waterSprite;
            this.container.addChild(n)
            return n;
        })
        node.opacity = 255;
        let pos = this.container.convertToNodeSpaceAR(this.waterPos.parent.convertToWorldSpaceAR(this.waterPos.getPosition()))
        // cc.log('startWater pos  ', pos.x, pos.y)
        let x = RandomHelper.random(0, this.waterPos.width)
        pos.x += x * OPPSITE[RandomHelper.random(0, OPPSITE.length)]
        node.setPosition(pos)
        cc.tween(node).by(1, { y: this.streamHigh }).call(() => {
            this.pool.put(node)
            node.opacity = 0;
            for (let index = 0; index < this.callback.length; index++) {
                const element = this.callback[index];
                if (element) {
                    element.emit([])
                }
            }
        }).start();
    }

    private time: number = 0;
    update(dt: number) {
        if (this.startFlag) {
            this.time += dt;
            if (this.time >= 0.1) {
                this.startWater()
                this.time = 0;
            }

        }
    }
}
